package dingyunchi.job.dao.impl;

import dingyunchi.job.dao.StudentDao;
import dingyunchi.job.entity.Student;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class StudentDaoImpl implements StudentDao {
    private final JdbcTemplate jdbcTemplate;

    public StudentDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public Student save(Student student) {
        String sql = "INSERT INTO student (name, age) VALUES (?,?)";
        jdbcTemplate.update(sql, student.getName(), student.getAge());
        Long id = jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", Long.class);
        student.setId(id);
        return student;
    }

    @Override
    public Student findById(Long id) {
        String sql = "SELECT * FROM student WHERE id =?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Student.class), id);
    }

    @Override
    public List<Student> findAll() {
        String sql = "SELECT * FROM student";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
    }

    @Override
    public void update(Student student) {
        String sql = "UPDATE student SET name =?, age =? WHERE id =?";
        jdbcTemplate.update(sql, student.getName(), student.getAge(), student.getId());
    }

    @Override
    public void delete(Long id) {
        String sql = "DELETE FROM student WHERE id =?";
        jdbcTemplate.update(sql, id);
    }
}